﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Role_el.Models;
using System.Web.Security;

namespace Role_el.Controllers
{
    public class LoginController : ApiController
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DelLogin([FromBody] Users user)
        {
            using (RolesDBEntities db = new RolesDBEntities())
            {
                Users us = db.Users.SingleOrDefault(p => p.LoginName == user.LoginName);
                List<int> rid = new List<int>();
                List<string> rolelist = new List<string>();
                var roleid = db.UserRoles.Where(x => x.UserId == us.Id).Select(x => new {
                    rid = x.Roled
                }).ToList();
                foreach (var item in roleid)
                {
                    rid.Add(Convert.ToInt32(item.rid));
                }
                foreach (var item in rid)
                {
                    var rolename = db.Roles.FirstOrDefault(x => x.Id == item);
                    rolelist.Add(rolename.Name);
                }
                if (us == null)
                {
                    return Json(new
                    {
                        code = -1,
                        msg = "用户不存在"
                    });
                }
                else
                {
                    if (us.IsLockout == 1)
                    {
                        return Json(new { code = -2, msg = "该用户已被锁定" });
                    }
                    else
                    {
                        if (us.Password != user.Password)
                        {
                            return Json(new
                            {
                                code = -1,
                                msg = "密码错误"
                            });
                        }
                        else
                        {
                            FormsAuthentication.SetAuthCookie(user.LoginName, true);
                            return Json(new
                            {
                                code = 0,
                                msg = "密码正确",
                                token = us.Id,
                                Id = us.Id,
                                RoleName = rolelist
                            });
                        }
                    }
                }
            }
        }
    }
}
